/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controlers.Admin;

import Pojos.ChiTietSanPham;
import Pojos.DanhMucSanPham;
import Pojos.HangSanXuat;
import Pojos.NhaPhanPhoi;
import Pojos.NhomSanPham;
import Pojos.SanPham;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import org.dom4j.DocumentException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.StringReader;
import javax.servlet.http.HttpSession;

/**
 *
 * @author ToanNhan
 */
@WebServlet(name = "CapNhatThongTinSanPhamControler", urlPatterns = {"/Admin/CapNhatThongTinSanPhamControler"})
public class CapNhatThongTinSanPhamControler extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        try {
            String command = request.getParameter("command");
            if (command == null) {
                response.sendRedirect("/WebsiteBanHang/Admin/CapNhatThongTinSanPham.jsp");
            } else {
                if (request.getParameter("btn") != null){
                    luuThongTinSanPham(request, response);
                }
                command = command.toLowerCase();
                if (command.compareTo("laysanpham") == 0) {
                    System.out.print("--------------------- lay san pham --------------");
                    laySanPham(request, response);
                }
                if (command.compareTo("laythongtinchitiet") == 0){
                    System.out.print("--------------------- lay chi tiet --------------");
                    layThongTinChiTiet(request, response);
                }
            }

        } finally {
        }
    }

    protected void luuThongTinSanPham(HttpServletRequest request, HttpServletResponse response) throws IOException{
        String maSanPham = request.getParameter("maSanPham");
        SessionFactory factory = new Configuration().configure("Pojos/hibernate.cfg.xml").buildSessionFactory();
        Session sessionHibernate = factory.openSession();
        Query query = sessionHibernate.createQuery("From SanPham Where maSanPham=?");
        query.setString(0, maSanPham);
        SanPham sp = (SanPham)query.uniqueResult();
        sp.setTenSanPham(request.getParameter("tenSanPham"));
        HttpSession session = request.getSession();
        if (session.getAttribute("hinhSanPham") != null){
            String hinhSanPham = (String) session.getAttribute("hinhSanPham");
            File file = new File(hinhSanPham);
            String name = file.getName().substring(0, file.getName().length() - 4);
            hinhSanPham = hinhSanPham.replaceAll(name, maSanPham);
            file.renameTo(new File(hinhSanPham));
            hinhSanPham = "/images/sanpham/" + maSanPham + file.getName().substring(file.getName().length() - 4);
            sp.setHinhSanPham(hinhSanPham);
        }

        sp.setGiaBan(Long.valueOf(request.getParameter("giaBan")));
        sp.setXuatXu(request.getParameter("xuatXu"));
        sp.setBaoHanh(request.getParameter("thongTinBaoHanh"));
        sp.setHangSanXuat(new HangSanXuat(request.getParameter("hangSanXuat"), ""));
        sp.setNhaPhanPhoi(new NhaPhanPhoi(request.getParameter("nhaPhanPhoi")));
        sp.setDanhMucSanPham(new DanhMucSanPham(request.getParameter("danhMucSanPham")));

        query = sessionHibernate.createQuery("from NhomSanPham where maNhomSanPham = ?");
        query.setString(0, sp.getNhomSanPham().getMaNhomSanPham());
        NhomSanPham nhomSanPham = (NhomSanPham) query.uniqueResult();

        sessionHibernate.close();
        factory.close();
        String mauChiTiet = nhomSanPham.getMauNhomChiTiet();
        String chiTiet = "";
        try {
            Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(mauChiTiet)));
            Node root = document.getFirstChild();
            NodeList childRoot = root.getChildNodes();
            int count = 1;
            for (int i = 0; i < childRoot.getLength(); i++) {
                NodeList elementChild = childRoot.item(i).getChildNodes();
                for (int j = 0; j < elementChild.getLength(); j++) {
                    NamedNodeMap map = elementChild.item(j).getAttributes();
                    map.item(1).setNodeValue(request.getParameter(String.valueOf(count)));
                    count++;
                }
            }
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(document);

            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(buffer);
            StreamResult result = new StreamResult(dos);
            transformer.transform(source, result);

            chiTiet = buffer.toString("UTF8");

        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(CapNhatThongTinSanPhamControler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerException ex) {
            Logger.getLogger(ThemSanPham.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(ThemSanPham.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
        }

        sp.getChiTietSanPham().setChiTiet(chiTiet);

        sessionHibernate = factory.openSession();
        sessionHibernate.beginTransaction();
        sessionHibernate.update(sp);
        sessionHibernate.getTransaction().commit();
        sessionHibernate.close();
        factory.close();
    }

    protected void layThongTinChiTiet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        SanPham sp = (SanPham) request.getAttribute("sanPham");
        SessionFactory factory = new Configuration().configure("Pojos/hibernate.cfg.xml").buildSessionFactory();
        Session session = factory.openSession();
        if (sp == null) {
            String maSanPham = request.getParameter("maSanPham");
            if (maSanPham != null) {
                Query query = session.createQuery("From SanPham Where maSanPham=?");
                query.setString(0, maSanPham);
                sp = (SanPham) query.uniqueResult();
                request.setAttribute(maSanPham, sp);
            } else {
                System.out.println("CapNhatThongTinSanPhamControler: Lay thong tin chi tiet san pham");
            }
        }
        String mauChiTiet = sp.getChiTietSanPham().getChiTiet();
        try {
            Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(mauChiTiet)));
            Node root = document.getFirstChild();
            NodeList childRoot = root.getChildNodes();
            String str = "<table width=\"90%\">";
            int m = 1;
            for (int i = 0; i < childRoot.getLength(); i++) {
                Node child = childRoot.item(i);
                str += "<tr bgcolor=\"bisque\"><td colspan=\"2\" align=\"center\">";
                str += child.getAttributes().item(0).getNodeValue();
                str += "</td></tr>";
                NodeList elementChild = child.getChildNodes();
                for (int j = 0; j < elementChild.getLength(); j++) {
                    if (m % 2 == 0) {
                        str += "<tr bgcolor=\"bisque\">";
                    } else {
                        str += "<tr>";
                    }

                    NamedNodeMap map = elementChild.item(j).getAttributes();
                    str += "<td width=\"200px\">" + map.item(0).getNodeValue() + "</td>";
                    str += "<td><input type=\"text\" style=\"width:300px;\" name=" + m + " value=\"" + map.item(1).getNodeValue() + "\"></input></td>";
                    str += "</tr>";
                    m++;
                }
            }
            if (m % 2 == 0) {
                str += "<tr bgcolor=\"bisque\">";
            } else {
                str += "<tr>";
            }

            str += "<td colspan=\"2\" align=\"center\"><input name=\"btn\" type=\"submit\" value=\"Lưu\"/></td></tr>";
            str += "</table>";            
            request.setAttribute("thongTinChiTiet", str);
            session.close();
            factory.close();
            request.getRequestDispatcher("CapNhatThongTinSanPham.jsp").forward(request, response);
        } catch (ParserConfigurationException ex) {
        } catch (SAXException ex) {
        }
    }

    protected void laySanPham(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String maSanPham = request.getParameter("maSanPham");
        if (maSanPham != null) {
            SessionFactory factory = new Configuration().configure("Pojos/hibernate.cfg.xml").buildSessionFactory();
            Session session = factory.openSession();
            Query query = session.createQuery("From SanPham Where maSanPham=?");
            query.setString(0, maSanPham);
            SanPham sp = (SanPham) query.uniqueResult();
            request.setAttribute("sanPham", sp);
            session.close();
            request.getRequestDispatcher("CapNhatThongTinSanPham.jsp").forward(request, response);
        } else {
            System.out.print("CapNhatThongTinThanhVienControler: Lay san pham");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
